package com.treeman.api.controller;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.treeman.api.ApiRequestError;
import com.treeman.api.ApiRequestError.ApiError;
import com.treeman.api.security.ApiAuthenticationManager;
import com.treeman.api.security.exception.InvalidUsernameOrPasswordException;
import com.treeman.user.User;
import com.treeman.user.UserRole;
import com.treeman.user.UserRole.Role;
import com.treeman.user.service.UserService;

@Controller
@RequestMapping(value = "/api")
public class ApiLoginController extends ApiExceptionResolverController {

	private static Logger log = Logger.getLogger(ApiLoginController.class);

	@Autowired
	private UserService userService;

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public @ResponseBody
	String login(HttpServletResponse respone,
			@RequestParam(value = "username", required = true) String username,
			@RequestParam(value = "password", required = true) String password)
			throws InvalidUsernameOrPasswordException {

		User authenticatedUser = userService.authenticateUser(username,
				password);
		Set<Role> userRoles = new HashSet<Role>();
		for (UserRole role : authenticatedUser.getUserRoles()) {
			userRoles.add(role.getRole());
		}

		String accessToken = ApiAuthenticationManager.generateToken();

		log.debug("Generated access_token: " + accessToken);

		ApiAuthenticationManager.getInstance().registerUserAccessToken(
				authenticatedUser, accessToken);

		return accessToken;
	}

	@ExceptionHandler(InvalidUsernameOrPasswordException.class)
	@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
	public @ResponseBody
	ApiRequestError handleWrongUsernameOrPasswordException(
			InvalidUsernameOrPasswordException e) {
		log.debug("InvalidUsernameOrPasswordException handled: "
				+ e.getLocalizedMessage());
		return new ApiRequestError(ApiError.INVALID_USERNAME_OR_PASSWORD,
				e.getLocalizedMessage());
	}
}
